package cn.sc.summer.feign.client;

import cn.sc.summer.constant.model.Result;
import cn.sc.summer.feign.config.FeignRequestConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.openfeign.FallbackFactory;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;

/**
 * 接口：order-server-feign
 *
 * @author a-xin
 * @date 2024-01-12 09:29:59
 */
@FeignClient(name = "${feign.client.server}", fallbackFactory = OssFeignClient.OssFeignFallback.class, configuration = FeignRequestConfig.class)
public interface OssFeignClient {

    /**
     * 上传文件
     *
     * @param uploadFile 文件流
     * @return 文件地址
     */
    @RequestMapping(value = "/oss/oss/uploadFile", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    Result<String> uploadFile(@RequestPart(value = "uploadFile") MultipartFile uploadFile);

    /**
     * 下载文件
     *
     * @param fileId   文件地址
     * @param response 返回数据信息
     * @return 文件地址
     */
    @RequestMapping(value = "/oss/oss/downloadFile", method = RequestMethod.GET)
    Result<String> downloadFile(@RequestParam(value = "fileId") String fileId, HttpServletResponse response);

    @Slf4j
    @Component
    class OssFeignFallback implements FallbackFactory<OssFeignClient> {
        @Override
        public OssFeignClient create(Throwable cause) {
            log.error("Fallback reason:{}", cause.getMessage());
            return new OssFeignClient() {

                /**
                 * 上传文件
                 *
                 * @param uploadFile 文件流
                 * @return 文件地址
                 */
                @Override
                public Result<String> uploadFile(MultipartFile uploadFile) {
                    return Result.fallback(cause.getMessage());
                }

                /**
                 * 下载文件
                 *
                 * @param fileId   文件地址
                 * @param response 返回数据信息
                 * @return 文件地址
                 */
                @Override
                public Result<String> downloadFile(String fileId, HttpServletResponse response) {
                    return Result.fallback(cause.getMessage());
                }
            };
        }
    }
}
